#include "stm32f10x.h"
#include "delay.h"
#include "CAN_IAP.h"
#include "led.h"

typedef void (*Funtion_t)(void);
uint32_t JumpAddr;
Funtion_t AppReset;

void MGPIO_Init(void)
{
	GPIO_InitTypeDef GPIO_InitStruct;
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_GPIOC,ENABLE);
	
	GPIO_InitStruct.GPIO_Mode 	= GPIO_Mode_Out_PP;
	GPIO_InitStruct.GPIO_Pin		= GPIO_Pin_5;
	GPIO_InitStruct.GPIO_Speed	= GPIO_Speed_50MHz;
	GPIO_Init(GPIOC,&GPIO_InitStruct);
	GPIO_InitStruct.GPIO_Pin		= GPIO_Pin_11;
	GPIO_Init(GPIOB,&GPIO_InitStruct);
	
	GPIOB->BSRR = GPIO_Pin_11;
	GPIOC->BSRR = GPIO_Pin_5;
}



int main(void)
{
	volatile uint8_t state;
	int reply;
	MGPIO_Init();
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	Delay_Init();
	Led_Init();
	IAP_CAN_Init();
	Led_On(1);
	while(1)
	{
		if( *((__IO uint32_t*)(UPGRADE_MARK_ADDR)) == 0xFFFFFFFF )
		{
			state = wait_HANDSHAKE();
			if(state == REPLY_HANDSHAKE)
			{
				FLASH_Unlock();
				reply = IAP_DownLoad();
				if(reply<0)
				{
					FLASH_ProgramWord(UPGRADE_MARK_ADDR,UPGRADE_WRITE_DATA);
					if(*((__IO uint32_t*)(UPGRADE_MARK_ADDR)) != 0xFFFFFFFF)
					{
						Led_On(0);
						FLASH_Lock();
					}
				 }
			}
		}
		else
		{
			if( (*((__IO uint32_t* )FLASH_APP1_ADDR) & 0x2FFE0000) == 0x20000000 )
			{
				JumpAddr = *((__IO uint32_t *)(FLASH_APP1_ADDR+4));
				AppReset = (Funtion_t)JumpAddr;
				__set_MSP( *((__IO uint32_t *)FLASH_APP1_ADDR) );
				AppReset();
			}
		}

			
	}

}
